from tornado.web import authenticated
from common.BaseHandler import BaseHandler
from common.Models import Author


class AuthorHandler(BaseHandler):
    @authenticated
    def get(self):
        author_obj = self.session.query(Author).filter_by(id=self.current_user, is_delete=0).first()
        if not author_obj:
            self.clear_cookie("author_id")
            self.redirect("/author/login")
        author_obj.name = author_obj.name if author_obj.name else ""
        author_obj.email = author_obj.email if author_obj.email else ""
        author_obj.password = author_obj.password if author_obj.password else ""
        author_obj.bio = author_obj.bio if author_obj.bio else ""
        self.render("management/author.html", author=author_obj)

    @authenticated
    def post(self):
        if "api" in self.request.uri:
            result = self.result()
            try:
                data = self.get_body()
                name = self.data_null(data, "name", "请输入用户名！")
                bio = self.data_null(data, "bio", "请输入个人说明！")
                email = self.data_null(data, "email", "请输入邮箱！")
                password = self.data_null(data, "password", "请输入密码！")
                author_obj = self.session.query(Author).filter_by(id=self.current_user, is_delete=0).first()
                if not author_obj:
                    self.clear_cookie("author_id")
                    self.redirect("/author/login")
                author_obj.name = name
                author_obj.bio = bio
                author_obj.email = email
                author_obj.password = password
                self.session.commit()
                result["status"] = 1
                result["msg"] = "信息更改成功！"
            except Exception as e:
                self.session.rollback()
                self.logger.error(e)
                result = self.check_except_zh(e)
            self.write(result)
        else:
            self.redirect("/author/info")
